接下來就來實作 store method。
/*
...
*/
class PostsController extends Controller
{
public function store(Request $request)
{
$auth_user = request()->get('auth_user')->first();
/*
...
*/
}
}
/*
...
*/
use Illuminate\Support\Facades\Validator;
class PostsController extends Controller
{
public function store(Request $request)
{
/*
...
*/
$rules = [
'title' => 'required|string|min:2|max:500',
'content' => 'required|string|min:2|max:1500'
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return response(['message' => $validator->errors()]);
}
/*
...
*/
}
}
/*
...
*/
use App\Post;
class PostsController extends Controller
{
public function store(Request $request)
{
/*
...
*/
$data = $request->only(['title', 'content']);
$data['user_id'] = $auth_user['id'];
$post = Post::create($data);
return response(['data' => $post]);
}
}
完整程式碼:
*PostsController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Post;
class PostsController extends Controller
{
public function store(Request $request)
{
$auth_user = request()->get('auth_user')->first();
$rules = [
'title' => 'required|string|min:2|max:500',
'content' => 'required|string|min:2|max:1500'
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return response(['message' => $validator->errors()]);
}
$data = $request->only(['title', 'content']);
$data['user_id'] = $auth_user['id'];
$post = Post::create($data);
return response(['data' => $post]);
}
}
未登入
缺少欄位
建立成功
之後再多建立幾篇貼文以及切換不同的使用者做同樣的動作 ( 此步驟忽略,為了之後的 method 做準備 ),完成後接下來就來實作 index 和 show。